package org.xx.armory.swing.components.formatters;

import javax.swing.text.DefaultFormatter;
import java.text.ParseException;

import static org.xx.armory.commons.SysUtils.removeNonDigit;
import static org.xx.armory.swing.components.FormatUtils.getPercentFormat;

public class PercentFormatter
        extends DefaultFormatter {
    public PercentFormatter(
    ) {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object stringToValue(
            String text
    )
            throws ParseException {
        try {
            return Double.parseDouble(removeNonDigit(text)) / 100;
        } catch (NumberFormatException ignore) {
            return null;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String valueToString(
            Object value
    ) {
        if (value instanceof Number) {
            return getPercentFormat().format(((Number) value).doubleValue() * 100);
        }
        return "";
    }
}
